package com.zhdl.network.prefirertu.analysis;

import cn.hutool.core.util.HexUtil;
import com.project.command.faq.analysis.ComAnalysis;
import com.project.command.faq.analysis.ComAnalysisData;
import com.project.command.faq.analysis.ComAnalysisResult;
import com.zhdl.network.prefirertu.dto.UpsFrameDto;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service(UpsAnalysis.UPS_ANALYSIS)
public class UpsAnalysis implements ComAnalysis<UpsFrameDto, ByteBuf> {
    public static final String UPS_ANALYSIS = "preFireUps";

    ByteBuf buf = Unpooled.buffer();// 无限制长度

    /**
     * com原始返回数据,进行解析
     * 将ByteBuf 数据,转换为list初步解析对象
     *
     * @param data
     * @return
     */
    @Override
    public ComAnalysisResult analysisData(ComAnalysisData<ByteBuf> data) {
        List<UpsFrameDto> list = splitBuff(data);
        if (!list.isEmpty()) {
            log.debug("拼接完整数据包个数为 : {}", list.size());
        }
        return new ComAnalysisResult<>(list);
    }


    private List<UpsFrameDto> splitBuff(ComAnalysisData<ByteBuf> data) {
        List<UpsFrameDto> fullFrames = new ArrayList<>();
        try {
            // 循环读取数据流中的数据，一个字节一个字节的读取
            // mark当前Index，如果无法处理，则重置index，再有数据时仍然从头开始匹配
            data.buf.markReaderIndex();
            while (data.buf.isReadable()) {
                int i = data.buf.readerIndex();
                int i1 = data.buf.readableBytes();
                UpsFrameDto fullDto = new UpsFrameDto();
                byte[] bytes = new byte[i1];
                data.buf.readBytes(bytes);
                fullDto.setFullBuff(bytes);
                fullFrames.add(fullDto);
            }
        } catch (Exception ex) {
            //从头开始读
            buf.resetReaderIndex();
            //打印错误数据信息
            byte[] bytes = new byte[buf.readableBytes()];
            buf.readBytes(bytes);
            log.info(HexUtil.encodeHexStr(bytes));
            //清除数据
            data.buf.clear();
            ex.printStackTrace();
        }
        return fullFrames;

    }

    /**
     * 获取协议头信息
     *
     * @return
     */
    @Override
    public String getHeadAnalysis() {
        return "";
    }

    /**
     * 协议追加校验位信息（尾部数据）
     *
     * @param cmdStr
     * @return
     */
    @Override
    public byte[] getAfterAnalysis(String cmdStr) {
        return HexUtil.decodeHex(cmdStr);
    }
}
